﻿using System;
using Fadada.FASC.SDK.DotNetCore.Interfaces;
using Fadada.FASC.SDK.DotNetCore.Model;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Fadada.FASC.SDK.DotNetCore.Attributes;
using Fadada.FASC.SDK.DotNetCore.Utils;
using Newtonsoft.Json;

namespace Fadada.FASC.SDK.DotNetCore.Services
{
    public class SignTaskDownloadFilesService : ISignTaskDownloadFilesService
    {
        public async Task<HttpWebResponse> GetFromHttpFileAsync(BaseInputInfo inputInfo, Dictionary<string, string> body, string token)
        {
            string strTimeStamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000).ToString();//毫秒值
            string strGUID = Guid.NewGuid().ToString("N");
            Dictionary<string, string> headerParames = new Dictionary<string, string>();//参数摘要计算得map
            headerParames.Add("X-FASC-App-Id", inputInfo.APP_ID);
            headerParames.Add("X-FASC-Sign-Type", "HMAC-SHA256");
            headerParames.Add("X-FASC-Timestamp", strTimeStamp);
            headerParames.Add("X-FASC-Nonce", strGUID);
            headerParames.Add("X-FASC-AccessToken", token);
            headerParames.Add("bizContent", GetFromBodyService.EncodeNonAsciiCharacters(body["bizContent"]));
            string strSign = SignUtil.GetSign(headerParames, strTimeStamp, inputInfo.APP_SECRET);

            headerParames.Add("X-FASC-Sign", strSign);
            //headerParames.Add("X-FASC-Sign", SignUtil.GetSign(headerParames.Union(body), strTimeStamp, inputInfo.APP_SECRET));
            var client = HttpWebHelp.CreateDefault(inputInfo.ReqDomainName + inputInfo.ReqEndPoint);
            foreach (var p in headerParames)
            {
                client.Headers[p.Key] = p.Value;
            }
            client.Method = "POST";
            client.ContentType = "application/x-www-form-urlencoded";
            string bodyParam = "bizContent=" + body["bizContent"];
            byte[] paramBytes = Encoding.UTF8.GetBytes(GetFromBodyService.EncodeNonAsciiCharacters(bodyParam));
            client.ContentLength = paramBytes.Length;
            using (Stream reqStream = client.GetRequestStream())
            {
                reqStream.Write(paramBytes, 0, paramBytes.Length);
            }

            var rspResponse = await Task.Run(() => client.GetResponseIgnoreServerError());
            return rspResponse;
        }

        public async Task<HttpWebResponse> GetSignTaskDownFilesAsync(SignTaskDownloadFiles signTaskDownloadFiles, BaseInputInfo inputInfo, string token)
        {
            var attributeInfo = GetUrlAttribute(signTaskDownloadFiles);
            inputInfo.ReqEndPoint = attributeInfo.Url;
            inputInfo.ReqMethod = attributeInfo.Method;
            var reqStr = JsonConvert.SerializeObject(signTaskDownloadFiles, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            var body = new Dictionary<string, string>() { { "bizContent", reqStr } };
            
            HttpWebResponse result = await GetFromHttpFileAsync(inputInfo, body, token);
            return result;
        }
        private RemoteServiceAttribute GetUrlAttribute(SignTaskDownloadFiles req)
        {
            var urlAttribute = req.GetType().GetCustomAttributes(false).First(r => r is RemoteServiceAttribute) as RemoteServiceAttribute;
            return urlAttribute;
        }
    }
}